<template>
  <Head title="订单管理 - Orange Tech" />
  <AdminLayout title="订单管理" subtitle="管理所有订单">
    <div class="space-y-6">
      <!-- 统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <div class="bg-white rounded-2xl p-6 shadow-sm">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
                <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">总订单数</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats.total_orders }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-2xl p-6 shadow-sm">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-orange-100 rounded-lg flex items-center justify-center">
                <svg class="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">待处理</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats.pending_orders + stats.processing_orders }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-2xl p-6 shadow-sm">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center">
                <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1" />
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">已支付金额</p>
              <p class="text-2xl font-semibold text-gray-900">¥{{ stats.paid_amount.toLocaleString() }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-2xl p-6 shadow-sm">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-indigo-100 rounded-lg flex items-center justify-center">
                <svg class="w-5 h-5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">总金额</p>
              <p class="text-2xl font-semibold text-gray-900">¥{{ stats.total_amount.toLocaleString() }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 筛选和搜索 -->
      <div class="bg-white rounded-lg p-6 shadow-sm">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
          <!-- 订单状态 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">订单状态</label>
            <select
              v-model="filters.status"
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900"
            >
              <option value="">全部状态</option>
              <option value="pending">待支付</option>
              <option value="processing">待发货</option>
              <option value="shipped">已发货</option>
              <option value="delivered">已送达</option>
              <option value="cancelled">已取消</option>
            </select>
          </div>

          <!-- 支付状态 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">支付状态</label>
            <select
              v-model="filters.payment_status"
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900"
            >
              <option value="">全部</option>
              <option value="pending">待支付</option>
              <option value="paid">已支付</option>
              <option value="failed">支付失败</option>
              <option value="refunded">已退款</option>
            </select>
          </div>

          <!-- 下单时间范围 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">开始日期</label>
            <input
              v-model="filters.date_from"
              type="date"
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">结束日期</label>
            <input
              v-model="filters.date_to"
              type="date"
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900"
            />
          </div>

          <!-- 金额区间 -->
          <div class="lg:col-span-2">
            <label class="block text-sm font-medium text-gray-700 mb-2">订单金额</label>
            <div class="flex items-center gap-2">
              <input
                v-model="filters.amount_min"
                type="number"
                placeholder="最低金额"
                class="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900"
              />
              <span class="text-gray-500">-</span>
              <input
                v-model="filters.amount_max"
                type="number"
                placeholder="最高金额"
                class="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900"
              />
            </div>
          </div>

          <!-- 搜索 -->
          <div class="lg:col-span-2">
            <label class="block text-sm font-medium text-gray-700 mb-2">搜索</label>
            <input
              v-model="filters.search"
              type="text"
              placeholder="订单号 / 收货人 / 手机号..."
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900"
              @keyup.enter="applyFilters"
            />
          </div>
        </div>

        <!-- 筛选按钮 -->
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-600">
            共 {{ orders.total || 0 }} 个订单
          </div>
          <div class="flex gap-2">
            <button
              @click="resetFilters"
              class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors"
            >
              重置
            </button>
            <button
              @click="applyFilters"
              class="px-4 py-2 border border-transparent rounded-md text-sm font-medium text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors"
            >
              应用筛选
            </button>
          </div>
        </div>
      </div>

      <!-- 批量操作 -->
      <div v-if="selectedOrders.length > 0" class="bg-blue-50 border border-blue-200 rounded-lg p-4">
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <span class="text-sm font-medium text-blue-900">
              已选择 {{ selectedOrders.length }} 个订单
            </span>
            <div class="flex space-x-2">
              <button
                @click="batchMarkAsPaid"
                class="px-3 py-1 bg-green-600 text-white text-sm rounded-md hover:bg-green-700 transition-colors"
              >
                标记为已支付
              </button>
              <button
                @click="batchShip"
                class="px-3 py-1 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 transition-colors"
              >
                标记为已发货
              </button>
              <button
                @click="batchCancel"
                class="px-3 py-1 bg-red-600 text-white text-sm rounded-md hover:bg-red-700 transition-colors"
              >
                取消订单
              </button>
            </div>
          </div>
          <button
            @click="clearSelection"
            class="text-blue-600 hover:text-blue-700 text-sm font-medium"
          >
            清除选择
          </button>
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="bg-white rounded-2xl shadow-sm overflow-hidden">
        <table class="w-full">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <input
                  type="checkbox"
                  :checked="isAllSelected"
                  @change="toggleSelectAll"
                  class="rounded border-gray-300 text-gray-900 focus:ring-gray-900"
                />
              </th>
              <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单号</th>
              <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户信息</th>
              <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">商品</th>
              <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">金额</th>
              <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">支付信息</th>
              <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
              <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-200">
            <tr v-for="order in orders.data" :key="order.id" class="hover:bg-gray-50">
              <!-- 复选框 -->
              <td class="px-6 py-4 whitespace-nowrap">
                <input
                  type="checkbox"
                  :value="order.id"
                  v-model="selectedOrders"
                  class="rounded border-gray-300 text-gray-900 focus:ring-gray-900"
                />
              </td>
              
              <!-- 订单号 -->
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900">{{ order.order_number }}</div>
                <div class="text-xs text-gray-500">ID: {{ order.id }}</div>
              </td>
              
              <!-- 用户信息 -->
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">{{ order.user?.name || '-' }}</div>
                <div class="text-xs text-gray-500">{{ order.user?.phone || order.user?.email || '-' }}</div>
              </td>
              
              <!-- 商品信息 -->
              <td class="px-6 py-4">
                <div class="text-sm text-gray-900">{{ order.items.length }} 件商品</div>
                <div v-if="order.items.length > 0" class="text-xs text-gray-500 truncate max-w-32">
                  {{ order.items[0].product_name }}
                  <span v-if="order.items.length > 1">等{{ order.items.length }}件</span>
                </div>
              </td>
              
              <!-- 金额 -->
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900">¥{{ order.total_amount.toLocaleString() }}</div>
                <div class="text-xs text-gray-500">含运费 ¥{{ order.shipping_fee.toLocaleString() }}</div>
              </td>
              
              <!-- 订单状态 -->
              <td class="px-6 py-4 whitespace-nowrap">
                <span
                  class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                  :class="getStatusClass(order.status)"
                >
                  {{ getStatusText(order.status) }}
                </span>
              </td>
              
              <!-- 支付信息 -->
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="space-y-1">
                  <span
                    class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                    :class="getPaymentStatusClass(order.payment_status)"
                  >
                    {{ getPaymentStatusText(order.payment_status) }}
                  </span>
                  <div class="text-xs text-gray-500">{{ getPaymentMethodText(order.payment_method) }}</div>
                </div>
              </td>
              
              <!-- 时间 -->
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">{{ formatDate(order.created_at) }}</div>
                <div v-if="order.paid_at" class="text-xs text-gray-500">支付: {{ formatDate(order.paid_at) }}</div>
              </td>
              
              <!-- 操作 -->
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <Link
                  :href="route('admin.orders.show', order.order_number)"
                  class="text-blue-600 hover:text-blue-700 font-medium"
                >
                  查看详情
                </Link>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 分页 -->
        <div v-if="orders.last_page > 1" class="px-6 py-4 border-t border-gray-200">
          <nav class="flex items-center justify-center gap-2">
            <Link
              v-for="link in orders.links"
              :key="link.label"
              :href="link.url"
              v-html="link.label"
              class="px-4 py-2 rounded-lg transition-colors"
              :class="link.active ? 'bg-gray-900 text-white' : 'bg-white border border-gray-300 text-gray-700 hover:bg-gray-50'"
            />
          </nav>
        </div>
      </div>
    </div>
  </AdminLayout>
</template>

<script setup>
import { reactive, ref, computed } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { useNotification } from '@/composables/useNotification'

const props = defineProps({
  orders: { type: Object, required: true },
  stats: { type: Object, required: true },
  filters: { type: Object, default: () => ({}) }
})

const { showSuccess, showError } = useNotification()

const filters = reactive({
  status: props.filters.status || '',
  payment_status: props.filters.payment_status || '',
  search: props.filters.search || '',
  date_from: props.filters.date_from || '',
  date_to: props.filters.date_to || '',
  amount_min: props.filters.amount_min || '',
  amount_max: props.filters.amount_max || ''
})

// 批量选择
const selectedOrders = ref([])

const isAllSelected = computed(() => {
  return props.orders.data.length > 0 && selectedOrders.value.length === props.orders.data.length
})

const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedOrders.value = []
  } else {
    selectedOrders.value = props.orders.data.map(order => order.id)
  }
}

const clearSelection = () => {
  selectedOrders.value = []
}

// 批量操作
const batchMarkAsPaid = () => {
  if (selectedOrders.value.length === 0) return
  
  if (!confirm(`确定要将选中的 ${selectedOrders.value.length} 个订单标记为已支付吗？`)) {
    return
  }
  
  router.post(route('admin.orders.batch-mark-paid'), {
    order_ids: selectedOrders.value
  }, {
    onSuccess: () => {
      showSuccess('批量操作成功', '已标记为已支付')
      clearSelection()
    },
    onError: () => {
      showError('批量操作失败', '请重试')
    }
  })
}

const batchShip = () => {
  if (selectedOrders.value.length === 0) return
  
  if (!confirm(`确定要将选中的 ${selectedOrders.value.length} 个订单标记为已发货吗？`)) {
    return
  }
  
  router.post(route('admin.orders.batch-ship'), {
    order_ids: selectedOrders.value
  }, {
    onSuccess: () => {
      showSuccess('批量操作成功', '已标记为已发货')
      clearSelection()
    },
    onError: () => {
      showError('批量操作失败', '请重试')
    }
  })
}

const batchCancel = () => {
  if (selectedOrders.value.length === 0) return
  
  if (!confirm(`确定要取消选中的 ${selectedOrders.value.length} 个订单吗？`)) {
    return
  }
  
  router.post(route('admin.orders.batch-cancel'), {
    order_ids: selectedOrders.value,
    reason: '批量取消'
  }, {
    onSuccess: () => {
      showSuccess('批量操作成功', '已取消订单')
      clearSelection()
    },
    onError: () => {
      showError('批量操作失败', '请重试')
    }
  })
}

const applyFilters = () => {
  router.get(route('admin.orders.index'), filters, {
    preserveState: true,
    preserveScroll: true
  })
}

const resetFilters = () => {
  filters.status = ''
  filters.payment_status = ''
  filters.search = ''
  filters.date_from = ''
  filters.date_to = ''
  filters.amount_min = ''
  filters.amount_max = ''
  applyFilters()
}

const getStatusText = (status) => {
  const map = {
    'pending': '待支付',
    'processing': '待发货',
    'shipped': '已发货',
    'delivered': '已送达',
    'cancelled': '已取消'
  }
  return map[status] || status
}

const getStatusClass = (status) => {
  const map = {
    'pending': 'bg-orange-100 text-orange-700 border border-orange-200',      // 橙色 - 待处理
    'processing': 'bg-blue-100 text-blue-700 border border-blue-200',         // 蓝色 - 处理中
    'shipped': 'bg-indigo-100 text-indigo-700 border border-indigo-200',      // 靛蓝 - 运输中
    'delivered': 'bg-green-100 text-green-700 border border-green-200',       // 绿色 - 已完成
    'cancelled': 'bg-red-100 text-red-700 border border-red-200'              // 红色 - 已取消
  }
  return map[status] || 'bg-gray-100 text-gray-700 border border-gray-200'
}

const getPaymentStatusText = (status) => {
  const map = {
    'pending': '待支付',
    'paid': '已支付',
    'failed': '支付失败',
    'refunded': '已退款'
  }
  return map[status] || status
}

const getPaymentStatusClass = (status) => {
  const map = {
    'pending': 'bg-orange-100 text-orange-700 border border-orange-200',      // 橙色 - 待支付
    'paid': 'bg-green-100 text-green-700 border border-green-200',            // 绿色 - 已支付
    'failed': 'bg-red-100 text-red-700 border border-red-200',                // 红色 - 支付失败
    'refunded': 'bg-gray-100 text-gray-700 border border-gray-200'            // 灰色 - 已退款
  }
  return map[status] || 'bg-gray-100 text-gray-700 border border-gray-200'
}

const getPaymentMethodText = (method) => {
  const map = {
    'alipay': '支付宝',
    'wechat': '微信支付',
    'cod': '货到付款',
    'mock': '模拟支付'
  }
  return map[method] || method || '-'
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

